/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringEscapeUtils;
import org.springblade.common.utils.WxSignatureUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.annotation.PreAuth;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.RoleConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.system.entity.ConfigWechatEnterprise;
import org.springblade.system.service.IConfigWechatEnterpriseService;
import org.springblade.system.vo.ConfigWechatEnterpriseVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;

/**
 * 企业微信登录配置 控制器
 *
 * @author BladeX
 * @since 2022-06-02
 */
@RestController
@AllArgsConstructor
@RequestMapping("/configwechatenterprise")
@Api(value = "企业微信登录配置", tags = "企业微信登录配置接口")
public class ConfigWechatEnterpriseController extends BladeController {

	private final IConfigWechatEnterpriseService configWechatEnterpriseService;

	@Resource
	private BladeRedis bladeRedis;
	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@PreAuth(RoleConstant.HAS_ROLE_ADMINISTRATOR)
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入configWechatEnterprise")
	public R<ConfigWechatEnterprise> detail(ConfigWechatEnterprise configWechatEnterprise) {
		ConfigWechatEnterprise detail = configWechatEnterpriseService.getOne(Condition.getQueryWrapper(configWechatEnterprise));
		return R.data(detail);
	}

	/**
	 * 分页 企业微信登录配置
	 */
	@GetMapping("/list")
	@PreAuth(RoleConstant.HAS_ROLE_ADMINISTRATOR)
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入configWechatEnterprise")
	public R<IPage<ConfigWechatEnterprise>> list(ConfigWechatEnterprise configWechatEnterprise, Query query) {
		IPage<ConfigWechatEnterprise> pages = configWechatEnterpriseService.page(Condition.getPage(query), Condition.getQueryWrapper(configWechatEnterprise));
		return R.data(pages);
	}

	/**
	 * 自定义分页 企业微信登录配置
	 */
	@GetMapping("/page")
	@PreAuth(RoleConstant.HAS_ROLE_ADMINISTRATOR)
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入configWechatEnterprise")
	public R<IPage<ConfigWechatEnterpriseVO>> page(ConfigWechatEnterpriseVO configWechatEnterprise, Query query) {
		IPage<ConfigWechatEnterpriseVO> pages = configWechatEnterpriseService.selectConfigWechatEnterprisePage(Condition.getPage(query), configWechatEnterprise);
		return R.data(pages);
	}

	/**
	 * 新增 企业微信登录配置
	 */
	@PostMapping("/save")
	@PreAuth(RoleConstant.HAS_ROLE_ADMINISTRATOR)
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入configWechatEnterprise")
	public R save(@Valid @RequestBody ConfigWechatEnterprise configWechatEnterprise) {
		return R.status(configWechatEnterpriseService.save(configWechatEnterprise));
	}

	/**
	 * 修改 企业微信登录配置
	 */
	@PostMapping("/update")
	@PreAuth(RoleConstant.HAS_ROLE_ADMINISTRATOR)
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入configWechatEnterprise")
	public R update(@Valid @RequestBody ConfigWechatEnterprise configWechatEnterprise) {
		return R.status(configWechatEnterpriseService.updateById(configWechatEnterprise));
	}

	/**
	 * 新增或修改 企业微信登录配置
	 */
	@PostMapping("/submit")
	@PreAuth(RoleConstant.HAS_ROLE_ADMINISTRATOR)
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入configWechatEnterprise")
	public R submit(@Valid @RequestBody ConfigWechatEnterprise configWechatEnterprise) {
		return R.status(configWechatEnterpriseService.saveOrUpdate(configWechatEnterprise));
	}


	/**
	 * 删除 企业微信登录配置
	 */
	@PostMapping("/remove")
	@PreAuth(RoleConstant.HAS_ROLE_ADMINISTRATOR)
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(configWechatEnterpriseService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 根据clientId获取租户ID
	 */
	@GetMapping("/tenant-by-client")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "根据clientId获取租户ID", notes = "传入clientId")
	public R<String> tenantByClient(String clientId) {
		if (StringUtil.isEmpty(clientId)) {
			return R.data(null);
		}
		ConfigWechatEnterprise detail = configWechatEnterpriseService.getOne(Wrappers.<ConfigWechatEnterprise>query().lambda().eq(ConfigWechatEnterprise::getClientId, clientId));
		if (!ObjectUtil.isNotEmpty(detail)) {
			return R.data(null);
		}
		return R.data(detail.getTenantId());
	}

	/**
	 * 获取微信配置
	 * params：前端传过来的，包含url
	 */
	@GetMapping("/getWxConfig")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "获取微信配置", notes = "params：前端传过来的，包含url")
	public R<Map<String, String>> gerWxConfig(ConfigWechatEnterpriseVO params) {
		try {
			String url = params.getUrl();
			url = StringEscapeUtils.unescapeHtml(url);
			String tenantId = params.getTenantId();
			if (StringUtil.isEmpty(tenantId)) {
				throw new ServiceException("租户ID无效!");
			}
			ConfigWechatEnterprise detail = configWechatEnterpriseService.getOne(Wrappers.<ConfigWechatEnterprise>query().lambda().eq(ConfigWechatEnterprise::getTenantId, tenantId));
			if (ObjectUtil.isEmpty(detail)) {
				throw new ServiceException("获取企业微信配置项失败!");
			}

			String ticket = bladeRedis.get("jsapi_ticket");
			Map<String, String> returnMap = WxSignatureUtil.getWechatSignature(url, detail.getClientId(), detail.getClientSecret(),ticket);
			bladeRedis.setEx("jsapi_ticket",returnMap.get("jsapi_ticket"),6000L);

			return R.data(returnMap);
		} catch (Exception e) {
			return R.data(null);
		}
	}
}
